/*
 * @Author: ૮₍ ˙О˙₎ა
 * @Date: 2023-07-12 18:19:45
 */
import { useUserInfoStore } from '@/stores/userInfo'
import axios, { type Method } from 'axios'
import { ElMessage } from 'element-plus'

// 创建axios实例
const instance = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 5000
})

// 添加请求拦截器
instance.interceptors.request.use(
  (config) => {
    const userInfoStore = useUserInfoStore()
    const token = userInfoStore.token

    if (token && config.headers) {
      config.headers.token = token
    }
    return config
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  (response) => {
    // 简化响应数据
    const res = response.data

    // 如果返回code不成功的判断
    if (res.code !== 200 && res.code !== 20000) {
      // 登录20001 token过期的逻辑处理
      if (res.code === 20001) {
        ElMessage({
          type: 'error',
          message: 'token过期,请重新登录',
          duration: 5000
        })
        // 登录过期退出登录
        // 获取userInfoStore实例
        const userInfoStore = useUserInfoStore()
        userInfoStore.reset()
        // 刷新页面清楚过期的用户信息
        // location.reload()
      } else {
        ElMessage({
          type: 'error',
          message: res.message || 'Error',
          duration: 5000
        })
      }
      // 将错误的信息继续传递下去
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  (error) => {
    ElMessage({
      type: 'error',
      message: error.message || '网络异常',
      duration: 5000
    })
    return Promise.reject(error)
  }
)

export interface IReqDataRes<T> {
  code: number
  data: T
  message: string
  success: boolean
}

/**
 * @description: 二次封装axios请求
 * @return {*}
 * @param {*} T
 */
const http = <T>(url: string, method: Method, data?: unknown) => {
  const newMeThod = method.toLocaleUpperCase()
  return instance.request<IReqDataRes<T>, IReqDataRes<T>>({
    url,
    method: newMeThod,
    params: newMeThod === 'GET' ? data : {},
    data: newMeThod === 'POST' || newMeThod === 'PUT' || newMeThod === 'DELETE' ? data : {}
  })
}

export { instance, http }
